import { getVideoBasicInfo } from './video-info'

export function getAssetUrl(url = '') {
  const u = url.replace(/\s/g, encodeURIComponent(' '))
  return `${import.meta.env.VITE_APP_ASSET_ORIGIN}${u}`
}

export function downloadFile(file: Blob, fileName: string) {
  const aElement = document.createElement('a')
  aElement.setAttribute('download', fileName)
  const href = URL.createObjectURL(file)
  aElement.href = href
  aElement.setAttribute('target', '_blank')
  aElement.click()
  URL.revokeObjectURL(href)
}

const ONE_M = 2 ** 20

export function validateImg(file: File): Promise<boolean> {
  return new Promise((resolve, reject) => {
    try {
      const fileType = file.type?.toLocaleLowerCase()
      if (!(['jpg', 'jpeg'].some(d => fileType.includes(d)))) {
        message.error('图片类型错误')
        return resolve(false)
      }

      if (file.size < ONE_M) {
        message.error('文件不得小于1M')
        return resolve(false)
      }
      if (file.size > 50 * ONE_M) {
        message.error('文件不得大于50M')
        return resolve(false)
      }

      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = function () {
        if (reader.readyState === 2) {
          const img = new Image()
          img.src = reader.result as string
          img.onload = function (e) {
            const target = e.target as HTMLImageElement
            const bool = target.height >= 768 && target.width > 1024
            resolve(bool)
          }
        }
      }
    }
    catch (error) {
      reject(error)
    }
  })
}

export async function validateVideo(file: File) {
  const url = URL.createObjectURL(file)
  try {
    const info = await getVideoBasicInfo(url)

    const { size, type } = file

    if (!type.includes('mp4')) {
      message.error('只可上传MP4文件')
      return false
    }

    if (size > 300 * ONE_M) {
      message.error('文件不得大于300M')
      return false
    }

    if (info.duration > 60) {
      message.error('视频时长超出1分钟')
      return false
    }

    return true
  }
  catch (error) {

  }
  finally {
    URL.revokeObjectURL(url)
  }
  return false
}

export function validatePDF(file: File) {
  if (!file.type.includes('pdf')) {
    message.error('只可上传PDF文件')
    return false
  }

  if (file.size > 50 * ONE_M) {
    message.error('文件不得大于50M')
    return false
  }
  return true
}

export function getFakeIp() {
  return new Array(4).fill('0').map(() => Math.floor(Math.random() * 255) + 1).join('.')
}

export function debounce(fn: Function, delay: number) {
  let timer: any
  return function (...args: any[]) {
    if (timer)
      clearTimeout(timer)

    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}
